﻿using System;
using System.Windows;

using Ones.ViewModels;

using TweetSharp.Twitter.Service;
using System.IO;

namespace Ones
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private AuthorizationViewModel _authViewModel;

        TwitterViewModel _tweetsViewModel;
        TwitterViewModel _mentionsViewModel;
        //DirectMessageViewModel _dmViewModel;
        TwitterService _service;
                
        private FileStream _str;

        public MainWindow()
        {
            InitializeComponent();

            _tweetsViewModel = (TwitterViewModel)this.DataContext;
            _mentionsViewModel = (TwitterViewModel)this.DataContext;
            //_dmViewModel = new DirectMessageViewModel();
            _authViewModel = new AuthorizationViewModel();

            LoadData();
            
            textUsername.Text = _service.GetUserProfile().ScreenName;
            _tweetsViewModel.LoadTweets(_service);
            _mentionsViewModel.LoadMentions(_service);
            //_dmViewModel.LoadDMs(_service);
            
        }

        private void LoadData()
        {
            Boolean fail = false;

            try
            {
                _str = new FileStream("users.ones", FileMode.Open);
                _str.Close();
                _service = _authViewModel.AuthenticateUserLocal();
                if (_service.Equals(null))
                {
                    fail = true;
                }
            }
            catch (FileNotFoundException ex)
            {
                fail = true;
                Console.WriteLine(ex.Message);
            }

            if (fail)
            {
                AuthenticationWindow authWindow = new AuthenticationWindow();

                while ((bool)authWindow.ShowDialog())
                {
                    if (!authWindow.IsAuthenticated)
                    {
                        throw new System.SystemException("The Twitter Service could not be initialized.");
                    }
                }

                _service = authWindow.Service;
            }
        }

        private void btnHome_Click(object sender, RoutedEventArgs e)
        {
            _tweetsViewModel.LoadTweets(_service);
        }

        private void btnMentions_Click(object sender, RoutedEventArgs e)
        {
            _mentionsViewModel.LoadMentions(_service);
        }

        private void btnDMs_Click(object sender, RoutedEventArgs e)
        {
            //_DMViewModel.LoadDMs(_service);
        }
    }
}
